﻿using System;
using System.Collections;
using System.Globalization;
using System.Net;

namespace Spiders
{
    class CookieUtility
    {
        /// <summary>
        /// 处理HttpWebResponse返回的响应头中的Set-Cookie首部   
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static ArrayList SetCookieStringHandler(string cookie)
        {
            char[] arr = cookie.ToCharArray();
            ArrayList list = new ArrayList();
            int j = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == ',' && arr[i + 1] != ' ')
                {
                    char[] sub = null;
                    if (j == 0)
                    {
                        sub = new char[i - j];
                        Array.Copy(arr, j, sub, 0, i - j);
                    }
                    else
                    {
                        sub = new char[i - j - 1];
                        Array.Copy(arr, j + 1, sub, 0, i - j - 1);
                    }
                    j = i;
                    string s = new string(sub);
                    list.Add(s);
                }
            }

            return list;
        }

        /// <summary>
        /// 将传入的Cookie字符串转换为Cookie对象并返回
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Cookie CookieHandler(string s, string key)
        {
            Cookie cookie = new Cookie();
            if (s.Contains("httponly"))
                cookie.HttpOnly = true;
            string[] arr = s.Split(';');
            for (int i = 0; i < arr.Length; i++)
            {
                if (!arr[i].Contains("=")) continue;
                string[] pair = arr[i].Split('=');
                if (pair[0].Trim() == key.ToUpper())
                {
                    cookie.Name = key.ToUpper();
                    cookie.Value = pair[1].Trim();
                }
                if (pair[0].Trim() == "expires")
                    cookie.Expires = DateTime.ParseExact(pair[1], "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
                if (pair[0].Trim() == "path")
                    cookie.Path = pair[1].Trim();
                if (pair[0].Trim() == "domain")
                    cookie.Domain = pair[1].Trim();
            }
            return cookie;
        }
    }
}
